<?php
namespace app\common\model;

use think\Db;
use think\Model;
use think\Session;

class Order extends Model
{
    public static function index($map = [], $page)
    {
        return Db::name('order')
            ->join('user', 'o_uid = u_id', 'left')
            ->where($map)
            ->field('o_id,o_uid, u_email, o_order_num,o_type,o_money_rmb,o_money_dollar,o_status,o_remark, from_unixtime(o_create_time) o_create_time, from_unixtime(o_update_time) o_update_time')
            ->order('o_status asc')
            ->order('o_id DESC')
            ->paginate(15, false, ['page' => $page]);
    }

    /**
     * 订单详情
     */
    public static function detail($id)
    {
        return Db::name('order')
            ->join('user', 'o_uid = u_id', 'left')
            ->where('o_id', $id)
            ->field('o_id,o_uid, u_email, o_order_num,o_type,o_money_rmb,o_money_dollar,o_status,o_remark, from_unixtime(o_create_time) o_create_time, from_unixtime(o_update_time) o_update_time')
            ->find();
    }

    /**
     * 修改订单的状态
     */
    public static function updateStatus($data)
    {
        //Db::name('user')->where('u_id', $uid)->setInc('u_integral',$u_integral);
        //setDec()：将数字字段值减少
        if ($data['o_status'] == 2) {//确认收款
            Db::startTrans();
            try{
                Db::name('order')->where('o_id', $data['o_id'])->where('o_status', 1)
                    ->update([
                        'o_status'  => 2,
                        'o_update_time' => time()
                    ]);
                Db::name('user')->where('u_id', $data['o_uid'])->setInc('u_dollar_balance', $data['o_money_dollar']);
                Db::commit();
                return true;
            } catch(\Exception $e) {
                Db::rollback();
                return false;
            }
        } elseif ($data['o_status'] == 3) {
            return Db::name('order')->where('o_id', $data['o_id'])->where('o_status', 1)
                ->update([
                    'o_status'  => 3,
                    'o_update_time' => time()
                ]);
        }else {
            return false;
        }
    }
    /**
     * =============================================================================
     */
    //用户充值
    public static function addOrder($data)
    {
        $o_order_num = 'cz'.$data['u_id'].time().rand(10000, 99999);
        $o_money_dollar = $data['o_money_rmb']/floatval(Systems::getexchange());
        return Db::name('order')->insertGetId([
            'o_uid'             => $data['u_id'],
            'o_order_num'       => $o_order_num,
            'o_type'            => $data['o_type'],
            'o_money_rmb'       => $data['o_money_rmb'],
            'o_money_dollar'    => $o_money_dollar,
            'o_status'          => 1,
            'o_remark'          => $data['o_remark'],
            'o_create_time'     => time(),
            'o_update_time'     => time(),
        ]);
    }
}